
NEW_VM_NAME=$1
IP=$2

usage()
{
  echo "cloudinit <vmname:master> <ip:110>"
  exit 1
}

if [ -z "${NEW_VM_NAME}" ] || [ -z "${IP}" ]; then
   usage
fi


cat > meta-data <<EOF
instance-id: ${NEW_VM_NAME}
local-hostname: ${NEW_VM_NAME}
EOF

cat > user-data << EOF
#cloud-config
users:
  - name: root
    sudo: ALL=(ALL) NOPASSWD:ALL
    ssh_authorized_keys:
      - ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILtCuBFCcSdruaExNgQjePIfs6bBnNc0s801ofuThDQ+ satway@dev
      - ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIGCONHZbTxi/GrIbOm/iemCguoCY3vGD87y0kmPBysxS root@cl-brain
    groups: users, sudo
    shell: /bin/bash
ssh_pwauth: True
disable_root: False
chpasswd:
  list: |
    root:Radi2025*
  expire: False    
write_files:
  - path: /etc/netplan/00-static-config.yaml
    permissions: '0600'
    content: |
      network:
        version: 2
        renderer: networkd
        ethernets:
          enp1s0:
            dhcp4: no
            addresses:
              - 192.168.1.$IP/24
            routes:
              - to: default
                via: 192.168.1.1
            nameservers:
              addresses: [192.168.1.1, 8.8.8.8, 1.1.1.1]

# 3. RUNTIME COMMANDS
runcmd:
  - timedatectl set-timezone Asia/Shanghai
  - rm /etc/netplan/50-cloud-init.yaml  # <--- REMOVE CONFLICTING DHCP FILE
  - netplan generate                   # <--- Process your new static config
  - netplan apply                      # <--- Apply the new config immediately
  - echo "Network configured via cloud-init."
EOF
TARGET_ISO=/var/lib/libvirt/images/cloud-init-${NEW_VM_NAME}.iso 
sudo genisoimage -output $TARGET_ISO  -volid cidata -joliet -rock user-data meta-data

NEW_VM_DISK="/var/lib/libvirt/images/${NEW_VM_NAME}.qcow2"
TEMPLATE_DISK="/var/lib/libvirt/images/app-template.qcow2"
sudo qemu-img create -f qcow2 -F qcow2  -b $TEMPLATE_DISK  $NEW_VM_DISK
echo "vm ${NEW_NAME}created"

# --- 3. Define and Start the VM ---

# Define RAM and VCPUS based on your needs (adjust as necessary)
VM_RAM_MB=$(( 64*1024 ))
VM_VCPUS=3

sudo virt-install \
    --name ${NEW_VM_NAME} \
    --ram ${VM_RAM_MB} \
    --vcpus ${VM_VCPUS} \
    --disk path=${NEW_VM_DISK},bus=virtio \
    --disk path=${TARGET_ISO},device=cdrom \
    --import \
    --os-variant ubuntu22.04 \
    --network bridge=virbr0,model=virtio \
    --graphics vnc,listen=0.0.0.0 \
    --console pty,target_type=serial

echo "VM ${NEW_VM_NAME} created and started. Connect with 'sudo virsh console ${NEW_VM_NAME}'"


